#include "widgettree.h"

#include <QBoxLayout>

WidgetTree::WidgetTree(QWidget* widget, int widgetType, QSplitter* splitter, WidgetTree* parent)
    : mParent(parent)
    , mWidget(widget)
    , mWidgetType(widgetType)
    , mSplitter(splitter)
    , QObject(parent)
{
    if (widgetType == SPLITTER) {
        mLayoutType = qobject_cast<QBoxLayout*>(widget->layout())->direction();
    }
}


QList<WidgetTree*> WidgetTree::Children() const
{
    return mChildren;
}

WidgetTree* WidgetTree::Parent() const
{
    return mParent;
}

WidgetTree* WidgetTree::Root() const
{
    auto tmp = Parent();
    while (tmp->Parent()) {
        tmp = tmp->Parent();
    }
    return tmp;
}

int WidgetTree::WidgetType() const
{
    return mWidgetType;
}

int WidgetTree::LayoutType() const
{
    return mLayoutType;
}

QWidget* WidgetTree::Widget() const
{
    return mWidget;
}

QSplitter* WidgetTree::Splitter() const
{
    return mSplitter;
}

void WidgetTree::setParent(QObject* parent)
{
    mParent = qobject_cast<WidgetTree*>(parent);
    QObject::setParent(parent);
}

void WidgetTree::addChild(QWidget* widget, int widgetType, QSplitter* splitter)
{
    addChild(new WidgetTree(widget, widgetType, splitter, this));
}

void WidgetTree::addChild(WidgetTree* child)
{
    mChildren.append(child);
    child->setParent(this);
}

void WidgetTree::removeChild(WidgetTree* child)
{
    mChildren.removeOne(child);
    child->setParent(nullptr);
}

void WidgetTree::Clear()
{
    foreach (const auto child, mChildren) {
        child->setParent(nullptr);
    }
    mChildren.clear();
}

WidgetTree* WidgetTree::findChild(QWidget* widget)
{
    if (this->Widget() == widget) {
        return this;
    }

    for (const auto child : mChildren) {
        if (auto result = child->findChild(widget); result != nullptr && result->Widget() == widget) {
            return result;
        }
    }

    return nullptr;
}

void WidgetTree::PrintTree() const
{
    qDebug("Node<%x>{widgetType=%d, layoutType=%d}", this, this->mWidgetType, this->mLayoutType);
    auto children = this->Children();
    while(!children.isEmpty()) {
        auto child = children.front();
        children.pop_front();
        children.append(child->Children());
        qDebug("Node<%x>{widgetType=%d, layoutType=%d, parent=%x}", child, child->mWidgetType, child->mLayoutType, child->Parent());
    }
}
